package com.whfc.ms.interceptor;

import com.whfc.common.result.Result;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.JSONUtil;
import com.whfc.common.util.SessionAttr;
import com.whfc.fuum.entity.SysUser;
import com.whfc.ms.redis.UserSessionRedisDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * @Description: 验证sessionId
 * @author: xugcheng
 * @version: 1.0
 * @date: 2020/1/8 9:56
 */
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserSessionRedisDao userSessionRedisDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        logger.debug("进入登录认证拦截器");
        // todo 参数验证
        Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = headers.nextElement();
            String headerValue = request.getHeader(headerName);
            logger.debug("{}:{}", headerName, headerValue);
        }

        // 登录验证
        Session session = SecurityUtils.getSubject().getSession();
        SysUser loginUser = (SysUser) session.getAttribute(SessionAttr.MS_USER);
        String loginMethod = (String) session.getAttribute(SessionAttr.LOGIN_METHOD);
        String thirdLogin = (String) session.getAttribute(SessionAttr.THIRD_LOGIN);
        String sgitgLogin = (String) session.getAttribute(SessionAttr.SGITG_LOGIN);

        // 账号密码登录和微信登录,不允许重复登录,需要验证sessionId是否一致
        if (SessionAttr.USERPASS_LOGIN.equals(loginMethod) || SessionAttr.WX_LOGIN.equals(loginMethod)) {
            if (loginUser != null) {
                String loginSessionId = userSessionRedisDao.getSessionId(loginUser.getId());
                String curSessionId = request.getSession().getId();
                logger.info("check login session {}", curSessionId.equals(loginSessionId));
                // if (!StringUtils.isEmpty(curSessionId) &&
                // curSessionId.equals(loginSessionId)) {
                return true;
                // }
            }
        }
        // 第三方免密登录
        else if (SessionAttr.THIRD_LOGIN.equals(loginMethod) || SessionAttr.THIRD_LOGIN.equals(thirdLogin)) {
            return loginUser != null;
        }
        Result result = new Result();
        result.setCode(ResultEnum.TOKEN_EXPIRED.getCode());
        result.setMsg(ResultEnum.TOKEN_EXPIRED.getMessage());
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSONUtil.toString(result));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}
